import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { initializeKeys } from './middleware/rsa-key-pair';
import { GlobalRsaKeyPairService } from './modules/global-module/rsa-key-pair/service';

const port = process.env.PORT ?? 3000;

async function bootstrap() {
  try {
    // 在app创建之前初始化 RSA 密钥对
    const { publicKey, privateKey } = initializeKeys();

    // 创建app
    const app = await NestFactory.create(AppModule);

    // 设置全局api前缀
    app.setGlobalPrefix('api');

    //  保存密钥
    const appConfigService = app.get(GlobalRsaKeyPairService);
    appConfigService.setRsaKeys(publicKey, privateKey);

    await app.listen(port);
    console.log(`serve is running at http://localhost:${port}`);
  } catch (error) {
    console.error('Failed to start the application:', error);
    process.exit(1);
  }
}

bootstrap();
